# Tower Defense game

import pygame
import towers
import common
import creeps
import player
import display
import toolbar
import sys

import profile

from pygame.locals import*

class Main:
    def __init__(self):
        pygame.init()
        
        screen = pygame.display.set_mode((752,608))
        common.load_images()
        self.draw = display.Window(screen)
        
        self.user = player.NewPlayer()
        self.user.ui = toolbar.UI(608,self.user)
        
        self.cswitch = 'off'
        self.ccycle = 1
        self.cpl = 10 # creeps per level
        self.clist = creeps.clist[:]
        
        self.buttons = []

    def creep_cycle(self):
        if self.ccycle%self.clist[self.user.creeplvl-1].spawnrate == 0:
            self.user.crp_list.append(self.clist[self.user.creeplvl-1](common.path))
            
            if self.ccycle/self.clist[self.user.creeplvl-1].spawnrate == self.cpl:
                self.ccycle = 1
                self.user.creeplvl += 1   
                self.cswitch = 'off'
        self.ccycle+=1
    
    def set_lists(self):
        self.buttons = []
        for obj in self.user.ui.elements:
            if obj.elem_type == 'button':
                self.buttons.append(obj)
                
            if obj.elem_type == 'scroll':
                self.buttons.append(obj) 
                
            if obj.elem_type == 'box':
                if obj.elements <> None:
                    for elem in obj.elements:
                        if elem.elem_type == 'button':
                            self.buttons.append(elem)
    def run(self):
        while(1):
            common.fps.tick(40)
            mx,my = pygame.mouse.get_pos()
            tx,ty = pygame.mouse.get_pos()
            
            self.set_lists()
            
            if self.cswitch == 'on':
                try:self.creep_cycle()           
                except IndexError: self.cswitch = 'off'
                                        
            if self.user.active_obj == None:
                '''pops up description for highlighted tower'''                       
                for btn in self.buttons:
                    if common.test_posrect((mx,my),btn.rect):
                        try:
                            self.user.ui.set_popup(btn.tower)
                        except:pass
                        break
                    else:
                        self.user.ui.set_popup(None)
            if self.user.active_obj <> None:
                tx = int(round((mx+self.user.active_obj.tower.x_offset)/16.0))*16
                ty = int(round((my+self.user.active_obj.tower.y_offset)/16.0))*16
            
            for event in pygame.event.get(): 
                if event.type == QUIT:
                    sys.exit(0)
                    
                if event.type == pygame.KEYDOWN:
                    if event.key == K_SPACE:
                        self.cswitch = 'on'
                        
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1: # left click                                                
                        if self.user.active_obj <> None: # tower being held
                            new_tower = self.user.active_obj.tower((tx+self.user.active_obj.tower.size[0]/2,ty+self.user.active_obj.size[1]/2),self.user)                            
                            if new_tower.place() == True:
                                self.user.twr_list.append(new_tower)
                                self.user.set_money(-new_tower.cost)
                            
                        elif self.user.active_obj == None:  # empty mouse                        
                                                        
                            for button in self.buttons:
                                button.click((mx,my),self.user)                                
                                
                            if mx < self.user.ui.x:
                                if self.user.selected_obj <> None:
                                    self.user.selected_obj.selected = False
                                self.user.selected_obj = None
                                self.user.active_obj = None
                                
                                for tower in self.user.twr_list:
                                    tower.selected = False
                                    
                                    if common.test_posrect((mx,my),tower.rect):
                                        tower.selected = True
                                        self.user.selected_obj = tower
                                  
                    if common.test_posrect((mx,my),self.user.ui.scroll_box.rect):
                        if event.button == 4:
                            self.user.ui.btn_scroll('up')
                        if event.button == 5:
                            self.user.ui.btn_scroll('down')
                                      
                    if event.button == 3: # right click
                        self.user.active_obj = None
                        if self.user.selected_obj <> None:
                            self.user.selected_obj.selected = False
                        self.user.selected_obj = None
                        
            for tower in self.user.twr_list: 
                tower.set_creeplist(self.user.crp_list)
                tower.set_target()
                tower.fire()
            deadcreeps = []                       
            for creep in self.user.crp_list:
                creep.tick()
                if creep.health <= 0:
                    self.user.set_money(creep.money)
                    deadcreeps.append(creep)
            for creep in deadcreeps:
                self.user.crp_list.remove(creep)
            self.user.ui.build(self.user.selected_obj)
            #print self.user.selected_obj,self.user.active_obj
            #except:self.user.ui.build(None)
            
            self.draw.update((tx,ty),self.user.twr_list,self.user.crp_list,self.user.ui,self.user.active_obj)
            
                    
                    
if __name__ == '__main__':
    td = Main()
    #profile.run("td.run()")
    td.run()